const context = require('./globalContext');
const { DB_INTERVAL, LOOP_INTERVAL, TriggerList, TriggerLog } = context;
const { Sandbox } = require('./sandbox');
const { MouseHandler } = require('../data/mouse');
const { MouseDao } = require('./dao/mouse');
const { TriggerDao } = require('./dao/trigger');
const { TriggerLogDao } = require('./dao/triggerLog');


const FIX_TRIGGER_ID = 1;

module.exports.Loop = () => {

    let trigger;

    setInterval(() => {
        TriggerDao.getOne(FIX_TRIGGER_ID, row => {
            trigger = row;
        });
    }, DB_INTERVAL);

    setInterval(() => {
        // let cur_price = context.PriceStack.cur().price;
        // let cur_time = Date.now();
        // for (const trigger of TriggerList) {
        //     let sb = new Sandbox({ sc: trigger.script, ctx: context });
        //     if (sb.runScript()) {
        //         for (const mouse of trigger.mouseList) {
        //             MouseHandler.clickPosStack(mouse.posList);
        //             let log = new TriggerLog({
        //                 's_id': trigger.id,
        //                 'p_id': mouse.id,
        //                 't_price': cur_price,
        //                 't_time': cur_time,
        //             });
        //             TriggerLogDao.addOne(log)
        //         }
        //         trigger.times++;
        //     }
        // }

        if (!context.TriggerSwitch || !trigger || !trigger.script) return;

        let sb = new Sandbox({ sc: trigger.script, ctx: context });

        if (!sb.runScript()) return;

        MouseDao.getLastPos(row => {
            if (!row) return;
            // console.log('Test Pos ID : ', row.id);
            MouseHandler.clickPosStack(JSON.parse(row.pos));

            let cur_price = context.PriceStack.cur();
            cur_price = cur_price && cur_price.price ? cur_price.price : 0;

            let log = new TriggerLog({
                's_id': trigger.id,
                'p_id': row.id,
                't_price': cur_price,
                't_time': Date.now()
            });

            TriggerLogDao.addOne(log);

            console.log('Triggered : %o', log);
        });

    }, LOOP_INTERVAL);
}
